<?php

namespace App\Http\Controllers;

use App\Events\OrderComputedDistribution;
use App\Http\Requests\PayRequest;
use App\Models\Order;
use App\User;
use EasyWeChat\Factory;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Str;

class PayController extends Controller
{

    /**
     * 微信支付
     *
     * @param PayRequest $request
     * @return mixed
     * @throws \EasyWeChat\Kernel\Exceptions\InvalidConfigException
     * @throws \Illuminate\Auth\Access\AuthorizationException
     */
    public function wehcatPay(PayRequest $request)
    {
        $app = Factory::payment(config('wechat.payment.default'));

        $user = $request->user();

        // 支付订单只能是未超时且没有关闭的订单
        $order = Order::where('order_sn', $request->input('order_sn'))
                ->where('ship_status', Order::SHIP_STATUS_AWAITING_PAYMENT)
                ->first();

        if (!is_null($order)) {
            $this->authorize('own', $order);
            $data = [
                'body' => '产品支付',
                'out_trade_no' => $order->order_sn,
                'total_fee' => bcmul($order->total_amount,100),
                'trade_type' => 'JSAPI',
                'openid' => $user->wx_mini_openid,
            ];
            if ($request->has('member_id') && !empty($request->member_id)) {
                $data['attach'] = json_encode(['member_id' => $request->member_id]);
                // 补全分享到商品信息
                $shared = User::find($request->member_id);
                if ($shared) {
                    event(new OrderComputedDistribution($order, $shared,1));
                }
            }
            Log::info("数据:",$data);
            $result = $app->order->unify($data);
            Log::info("支付结果数据:",$result);
            if ($result['return_code'] == 'SUCCESS' && $result['result_code'] == 'SUCCESS') {
                $prepayId = $result['prepay_id'];
                // 将prepayId 存起来，支付成功之后通知
                $config = $app->jssdk->sdkConfig($prepayId);
                $order->extra = json_encode(['prepayid' => $prepayId]);
                $order->save();
                return $this->success($config);
            }
            if ($result['return_code'] == 'FAIL' && array_key_exists('return_msg', $result)) {
                return $this->failed($result['return_msg']);
            }
            return $this->failed($result['err_code_des'] ?? '支付失败');
        }else {
            return $this->failed('支付超时或已支付完成,请重新下单');
        }
    }
}
